<?php
/**
 * Copyright (c) [2019] [吴跃忠]
 * [selibra] is licensed under the Mulan PSL v1.
 * You can use this software according to the terms and conditions of the Mulan PSL v1.
 * You may obtain a copy of Mulan PSL v1 at:
 * http://license.coscl.org.cn/MulanPSL
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v1 for more details.
 */

namespace Selibra\Http\Interceptor;


use Selibra\Tools\Console;

class RequestSpaceTree
{

    /**
     * @var RequestSpaceNode[]
     */
    protected array $nodeTree = [];


    /**
     * @param array $tree
     * @param RequestSpaceTree $node
     */
    public function addNode(array $tree, RequestSpaceNode $node)
    {
        if (count($tree) === 1) {
            // 如果存在
            $nodeName = reset($tree);
            if (!empty($this->nodeTree[$nodeName])) {
                if (strpos('/', $nodeName) === false) {
                    $tree[] = '/';
                    $node->setNodeName('/');
                }
                $this->addNode($tree, $node);
            } else {
                $this->nodeTree[$nodeName][] = $node;
            }
        } else {
            $nodeName = array_shift($tree);
            if (empty($this->nodeTree[$nodeName])) {
                // 创建一个新节点
                $this->nodeTree[$nodeName] = new RequestSpaceNode($nodeName);
            }
            if (is_array($this->nodeTree[$nodeName])) {
                // 把当前节点的数组转换为node
                /** @var RequestSpaceNode[] $nodes */
                $nodes = $this->nodeTree[$nodeName];
                $newNode = new RequestSpaceNode($nodeName);
                foreach ($nodes as $nodeItem) {
                    $newNode->getTree()->addNode([$nodeItem->getNodeName()], $nodeItem);
                }
                $newNode->getTree()->addNode($tree, $node);
                $this->nodeTree[$nodeName] = $newNode;
            } else {
                $this->nodeTree[$nodeName]->getTree()->addNode($tree, $node);
            }
        }
    }


    /**
     * @param array $tree
     * @return RequestSpaceNode[]
     */
    public function getNodes(array $tree)
    {
        if (count($tree) === 1) {
            if (!array_key_exists($tree[0], $this->nodeTree)) {
                return [];
            }
            return $this->nodeTree[$tree[0]];
        } else {
            $nodeName = array_shift($tree);
            if (empty($this->nodeTree[$nodeName])) {
                // 创建一个新节点
                return [];
            } elseif (is_array($this->nodeTree[$nodeName])) {
                return $this->nodeTree[$nodeName];
            }
            return $this->nodeTree[$nodeName]->getTree()->getNodes($tree);
        }
    }

}